"use client"

import { useState, useRef, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Animated, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, List, Lightbulb } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "../../constants/theme"
import { WordListModal } from "../../components/practices/WordListModal"
import { ProgressBar } from "../../components/practices/ProgressBar"
import { NaturalReadingCard } from "../../components/practices/NaturalReadingCard"

// 模拟的练习数据
const PRACTICE_DATA = [
    {
        id: "1",
        word: "funny",
        phonetic: "/ˈfʌni/",
        type: "adj",
        meaning: "滑稽的；好笑的；有趣的",
        parts: ["fu", "nny"],
    },
    {
        id: "2",
        word: "happy",
        phonetic: "/ˈhæpi/",
        type: "adj",
        meaning: "快乐的；幸福的；高兴的",
        parts: ["ha", "ppy"],
    },
    {
        id: "3",
        word: "beautiful",
        phonetic: "/ˈbjuːtɪfʊl/",
        type: "adj",
        meaning: "美丽的；漂亮的",
        parts: ["beau", "ti", "ful"],
    },
    // ... 更多单词
]

// 提示状态枚举
enum HintState {
    None = 0,
    Phonetic = 1,
    Word = 2,
}

export default function NaturalSpellScreen() {
    const router = useRouter()
    const [currentIndex, setCurrentIndex] = useState(0)
    const [selectedParts, setSelectedParts] = useState<string[]>([])
    const [hintState, setHintState] = useState<HintState>(HintState.None)
    const [listModalVisible, setListModalVisible] = useState(false)
    const hintTimeoutRef = useRef<NodeJS.Timeout>()

    // 动画值
    const hintButtonScale = useRef(new Animated.Value(1)).current
    const contentOpacity = useRef(new Animated.Value(1)).current
    const wordOpacity = useRef(new Animated.Value(0)).current

    // 当前单词
    const currentWord = PRACTICE_DATA[currentIndex]

    // 添加状态来跟踪反馈
    const [feedback, setFeedback] = useState<{ type: "success" | "error" | null; message: string }>({
        type: null,
        message: "",
    })

    // 显示提示
    const toggleHint = () => {
        // 缩放提示按钮
        Animated.sequence([
            Animated.timing(hintButtonScale, {
                toValue: 0.8,
                duration: 100,
                useNativeDriver: true,
            }),
            Animated.timing(hintButtonScale, {
                toValue: 1,
                duration: 100,
                useNativeDriver: true,
            }),
        ]).start()

        // 淡入淡出动画
        Animated.sequence([
            Animated.timing(contentOpacity, {
                toValue: 0,
                duration: 200,
                useNativeDriver: true,
            }),
            Animated.timing(contentOpacity, {
                toValue: 1,
                duration: 200,
                useNativeDriver: true,
            }),
        ]).start()

        // 更新提示状态
        if (hintState === HintState.None) {
            // 从无提示到显示音标
            setHintState(HintState.Phonetic)

            // 显示单词动画
            Animated.timing(wordOpacity, {
                toValue: 0,
                duration: 0,
                useNativeDriver: true,
            }).start()
        } else if (hintState === HintState.Phonetic) {
            // 从音标到显示单词
            setHintState(HintState.Word)

            // 显示单词动画
            Animated.timing(wordOpacity, {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }).start()

            // 3秒后隐藏单词
            if (hintTimeoutRef.current) {
                clearTimeout(hintTimeoutRef.current)
            }
            hintTimeoutRef.current = setTimeout(() => {
                // 隐藏单词动画
                Animated.timing(wordOpacity, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }).start(() => {
                    setHintState(HintState.None)
                })
            }, 3000)
        } else {
            // 从显示单词回到无提示
            setHintState(HintState.None)

            // 隐藏单词动画
            Animated.timing(wordOpacity, {
                toValue: 0,
                duration: 300,
                useNativeDriver: true,
            }).start()
        }
    }

    // 清理定时器
    useEffect(() => {
        return () => {
            if (hintTimeoutRef.current) {
                clearTimeout(hintTimeoutRef.current)
            }
        }
    }, [])

    // 选择单词部分
    const handlePartSelect = (part: string) => {
        // 检查是否已经选择了这个部分
        const partIndex = selectedParts.indexOf(part)

        if (partIndex !== -1) {
            // 如果已经选择了，则移除它
            const newSelectedParts = [...selectedParts]
            newSelectedParts.splice(partIndex, 1)
            setSelectedParts(newSelectedParts)
            return
        }

        if (selectedParts.length < currentWord.parts.length) {
            const newSelectedParts = [...selectedParts, part]
            setSelectedParts(newSelectedParts)

            // 检查是否已经选择了所有部分，如果是，则验证答案
            if (newSelectedParts.length === currentWord.parts.length) {
                // 检查答案是否正确
                const correct = newSelectedParts.every((part, index) => part === currentWord.parts[index])

                if (correct) {
                    // 如果正确，显示成功反馈
                    setFeedback({ type: "success", message: "拼写正确！" })

                    // 延迟后跳转到下一个单词
                    setTimeout(() => {
                        if (currentIndex < PRACTICE_DATA.length - 1) {
                            setCurrentIndex(currentIndex + 1)
                            setSelectedParts([])
                            setHintState(HintState.None)
                            setFeedback({ type: null, message: "" })
                        }
                    }, 1200)
                } else {
                    // 如果错误，显示错误反馈
                    setFeedback({ type: "error", message: "拼写错误，请重试" })

                    // 延迟后清空选择
                    setTimeout(() => {
                        setSelectedParts([])
                        setFeedback({ type: null, message: "" })
                    }, 1200)
                }
            }
        }
    }

    // 移除单词部分
    const handlePartRemove = (index: number) => {
        const newSelectedParts = [...selectedParts]
        newSelectedParts.splice(index, 1)
        setSelectedParts(newSelectedParts)
    }

    // 下一个单词
    const handleNext = () => {
        if (currentIndex < PRACTICE_DATA.length - 1) {
            // 添加滑动淡出动画
            Animated.timing(contentOpacity, {
                toValue: 0,
                duration: 250,
                useNativeDriver: true,
            }).start(() => {
                setCurrentIndex(currentIndex + 1)
                setSelectedParts([])
                setHintState(HintState.None)
                setFeedback({ type: null, message: "" })

                // 添加滑动淡入动画
                Animated.timing(contentOpacity, {
                    toValue: 1,
                    duration: 250,
                    useNativeDriver: true,
                }).start()
            })
        }
    }

    return (
        <View style={styles.container}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                <SafeAreaView style={styles.safeArea} edges={["top"]}>
                    {/* 头部 */}
                    <View style={styles.header}>
                        <TouchableOpacity onPress={() => router.back()} style={styles.headerButton}>
                            <ArrowLeft size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>
                        <Text style={styles.headerTitle}>自然拼读</Text>
                        <TouchableOpacity onPress={() => setListModalVisible(true)} style={styles.headerButton}>
                            <List size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>
                    </View>

                    {/* 进度条 */}
                    <ProgressBar current={currentIndex + 1} total={PRACTICE_DATA.length} showText={true} textPosition="top" />

                    {/* 主要内容区域 */}
                    <View style={styles.contentWrapper}>
                        <View style={styles.content}>
                            <View style={styles.card}>
                                <NaturalReadingCard
                                    word={currentWord.word}
                                    phonetic={currentWord.phonetic}
                                    type={currentWord.type}
                                    meaning={currentWord.meaning}
                                    parts={currentWord.parts}
                                    showPhonetic={hintState >= HintState.Phonetic}
                                    showWord={hintState === HintState.Word}
                                    contentOpacity={contentOpacity}
                                    wordOpacity={wordOpacity}
                                    onPartSelect={handlePartSelect}
                                    onPartRemove={handlePartRemove}
                                    selectedParts={selectedParts}
                                    feedback={feedback}
                                />
                            </View>
                        </View>
                    </View>
                </SafeAreaView>

                {/* 底部状态栏 */}
                <View style={styles.bottomBar}>
                    <Animated.View style={{ transform: [{ scale: hintButtonScale }] }}>
                        <TouchableOpacity style={styles.hintButton} onPress={toggleHint}>
                            <Lightbulb size={24} color={theme.colors.primary.default} />
                        </TouchableOpacity>
                    </Animated.View>

                    <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
                        <LinearGradient
                            colors={theme.colors.primary.gradient}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 0 }}
                            style={styles.nextButtonGradient}
                        >
                            <Text style={styles.nextButtonText}>下一词</Text>
                        </LinearGradient>
                    </TouchableOpacity>
                </View>

                {/* 单词列表弹窗 */}
                <WordListModal
                    visible={listModalVisible}
                    data={PRACTICE_DATA.map((item) => ({
                        id: item.id,
                        word: item.word,
                        phonetic: item.phonetic,
                        meaning: item.meaning,
                    }))}
                    currentIndex={currentIndex}
                    onClose={() => setListModalVisible(false)}
                    onSelectWord={(index) => {
                        // 添加动画效果
                        Animated.timing(contentOpacity, {
                            toValue: 0,
                            duration: 250,
                            useNativeDriver: true,
                        }).start(() => {
                            setCurrentIndex(index)
                            setSelectedParts([])
                            setHintState(HintState.None)
                            setListModalVisible(false)

                            // 添加滑动淡入动画
                            Animated.timing(contentOpacity, {
                                toValue: 1,
                                duration: 250,
                                useNativeDriver: true,
                            }).start()
                        })
                    }}
                    title="单词列表"
                />
            </LinearGradient>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    safeArea: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    headerButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        textAlign: "center",
    },
    contentWrapper: {
        flex: 1,
        paddingBottom: Platform.OS === "ios" ? 90 : 70, // 增加底部边距，避免内容被底部栏遮挡
    },
    content: {
        flex: 1,
        paddingHorizontal: theme.spacing.lg,
        paddingTop: theme.spacing.lg,
    },
    card: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge, // 增加圆角
        padding: theme.spacing.xl,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    bottomBar: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingTop: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
        backgroundColor: theme.colors.neutral.white,
        borderTopWidth: 1,
        borderTopColor: "rgba(0, 0, 0, 0.05)",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.05)",
                shadowOffset: { width: 0, height: -2 },
                shadowOpacity: 1,
                shadowRadius: 4,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    hintButton: {
        width: 44,
        height: 44,
        borderRadius: 22,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    nextButton: {
        flex: 1,
        marginLeft: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        height: 44, // 固定高度
    },
    nextButtonGradient: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
    },
    nextButtonText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
    },
})

